package com.sinaapp.gavinzhang.ConcurrentProgramming;

import java.util.Random;
import java.util.concurrent.*;

/**
 * CyclicBarrier 可用于多次计数
 * Created by gavin on 15-9-1.
 */
public class CyclicBarrierTest {
    public static void main(String[] args)
    {
        ExecutorService executorService = new ThreadPoolExecutor(5,5,6000L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
        for (int i = 0; i < 5; i++) {
            executorService.execute(new Runner(cyclicBarrier));
        }
    }
}

class Runner implements Runnable{
    private CyclicBarrier cyclicBarrier;

    public void run() {
        try {
            Thread.sleep(new Random().nextInt(3000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" 进入跑道");
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName()+" 开始跑步");
        try {
            Thread.sleep(new Random().nextInt(9000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" 跑完了");

        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName()+" 这场比赛结束");
    }

    public Runner(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }
}
